package com.lwq.fast.log.fastlogserver.rabbitmq.listener;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.lwq.fast.log.fastlogcore.constant.Constants;
import com.lwq.fast.log.fastlogcore.entity.Message;
import com.lwq.fast.log.fastlogserver.es.service.ElasticSearchService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 消息监听器，监听rabbitmq消息
 * @author 刘文强
 */
@Configuration
@ConditionalOnProperty(name = "active.client", havingValue = "rabbitMq")
@Slf4j
public class BatchRabbitConsumerListener {

    @Autowired
    private ElasticSearchService elasticSearchService;

    @RabbitListener(queues = Constants.QUEUE, containerFactory = "consumerBatchContainerFactory")
    public void listenerMessage(List<String> msgList, Channel channel) {
        batchInsert(msgList);
        try {
            channel.basicAck(msgList.size(), true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    private void batchInsert(List<String> msgList) {
        List<Message> messageList = new ArrayList<>();
        for (String msg : msgList) {
            try{
                Message message = JSON.parseObject(msg, Message.class);
                if (ObjectUtil.isNotNull(message)){
                    messageList.add(message);
                }
            }catch (Exception e){
                // 序列化出错，静默处理
            }
        }
        if (CollectionUtil.isNotEmpty(messageList)){
            try{
                elasticSearchService.logMessage2EsBatch(messageList);
            }catch (Exception e){
                log.error("批量写入数据到Es出错",e);
            }
        }
    }
}
